#!/bin/sh

set -euo pipefail

base=$( dirname "${BASH_SOURCE[0]}")

if ! ci=$( which ci-operator 2>/dev/null ); then
  ci="${base}/../ci-operator/ci-operator"
fi

arg1=(${1//\// })
org=${arg1[0]}
repo=${arg1[1]}
branch=master
variant=
if [[ -n "${arg1[2]-}" ]]; then
  branch=${arg1[2]}
fi
if [[ -n "${arg1[3]-}" ]]; then
  variant=__${arg1[3]}
fi

ref=$org/$repo@$branch
if [[ -n "${2-}" ]]; then
  ref=$2
fi

function mkpr {
  repo="${1}"
  ref="${2}"

  if [[ -z "${2}" ]]; then
    echo "error: must specify branch" 1>&2
    exit 1
  fi
  branch_ref="$( git ls-remote https://github.com/${repo}.git refs/heads/${ref} | cut -f 1 -d $'\t' )"
  if [[ -z "${branch_ref}" ]]; then
    echo "error: no ref found for ${ref}" 1>&2
    exit 1
  fi

  if [[ -n "${3-}" ]]; then
    pr_ref="$( git ls-remote https://github.com/${repo}.git refs/pull/${3}/head | cut -f 1 -d $'\t' )"
    if [[ -z "${pr_ref}" ]]; then
      echo "error: no PR ref found for ${3}" 1>&2
      exit 1
    fi
    echo "-base-ref ${ref} -base-sha ${branch_ref} -pull-author unknown -pull-number ${3} -pull-sha ${pr_ref}"
    exit 0
  fi

  echo "-base-ref ${ref} -base-sha ${branch_ref}"
}

if [[ -z "${PROW_BUILD-}" ]]; then
  ${ci} --report-address "" --unresolved-config "${base}/../ci-operator/config/$org/$repo/$org-$repo-$branch$variant.yaml" --git-ref $ref --target [images]
  exit 0
fi

mkpj -config-path core-services/prow/02_config/_config.yaml -job-config-path ./ci-operator/jobs/ -job branch-ci-$org-$repo-$branch-images $( mkpr $org/$repo $branch ) | oc create -f - -n ci | cut -f 2- -d '/'
